<template>
  <div class="excel-container">
    <!-- 优化后的工具栏 -->
    <div class="format-toolbar">
      <!-- 文件操作组 -->
      <div class="toolbar-group">
        <el-button type="primary" @click="saveData" title="保存">
          <i class="el-icon-document-checked"></i> 保存
        </el-button>
        <el-button @click="exportExcel" title="导出Excel">
          <i class="el-icon-download"></i> 导出
        </el-button>
        <el-button @click="importExcel" title="导入Excel">
          <i class="el-icon-upload2"></i> 导入
        </el-button>
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          accept=".xlsx, .xls"
          @change="handleFileImport"
        />
      </div>
      
      <!-- 字体设置组 -->
      <div class="toolbar-group">
        <el-select v-model="fontFamily" placeholder="字体" @change="applyFontFamily" size="small">
          <el-option label="宋体" value="SimSun"></el-option>
          <el-option label="微软雅黑" value="Microsoft YaHei"></el-option>
          <el-option label="Arial" value="Arial"></el-option>
          <el-option label="Times New Roman" value="Times New Roman"></el-option>
        </el-select>
        
        <el-select v-model="fontSize" placeholder="字号" @change="applyFontSize" size="small" style="width: 80px;">
          <el-option v-for="size in [8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72]" 
                    :key="size" :label="`${size}px`" :value="size"></el-option>
        </el-select>
      </div>
      
      <!-- 文本格式组 -->
      <div class="toolbar-group">
        <el-button-group>
          <el-button size="small" :class="{ 'active': isBold }" @click="toggleBold" title="加粗">
            <i class="el-icon-bold"></i>
          </el-button>
          <el-button size="small" :class="{ 'active': isItalic }" @click="toggleItalic" title="斜体">
            <i class="el-icon-italic"></i>
          </el-button>
          <el-button size="small" :class="{ 'active': isUnderline }" @click="toggleUnderline" title="下划线">
            <i class="el-icon-underline"></i>
          </el-button>
        </el-button-group>
      </div>
      
      <!-- 对齐方式组 -->
      <div class="toolbar-group">
        <el-button-group>
          <el-button size="small" @click="applyAlignment('htLeft')" title="左对齐">
            <i class="el-icon-align-left"></i>
          </el-button>
          <el-button size="small" @click="applyAlignment('htCenter')" title="居中对齐">
            <i class="el-icon-align-center"></i>
          </el-button>
          <el-button size="small" @click="applyAlignment('htRight')" title="右对齐">
            <i class="el-icon-align-right"></i>
          </el-button>
        </el-button-group>
      </div>
      
      <!-- 颜色设置组 -->
      <div class="toolbar-group">
        <span class="color-label">文字:</span>
        <el-color-picker v-model="textColor" size="small" @change="applyTextColor" title="文字颜色"></el-color-picker>
        <span class="color-label">背景:</span>
        <el-color-picker v-model="bgColor" size="small" @change="applyBgColor" title="背景颜色"></el-color-picker>
      </div>
      
      <!-- 单元格操作组 -->
      <div class="toolbar-group">
        <el-button-group>
          <el-button size="small" @click="mergeCells" title="合并单元格">
            <i class="el-icon-s-operation"></i> 合并
          </el-button>
          <el-button size="small" @click="unmergeCells" title="取消合并">
            <i class="el-icon-s-unfold"></i> 取消合并
          </el-button>
        </el-button-group>
      </div>
      
      <!-- 边框设置组 -->
      <div class="toolbar-group">
        <el-dropdown @command="handleBorderCommand" trigger="click">
          <el-button size="small">
            <i class="el-icon-s-grid"></i> 边框 <i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="all">所有边框</el-dropdown-item>
              <el-dropdown-item command="outer">外边框</el-dropdown-item>
              <el-dropdown-item command="none">无边框</el-dropdown-item>
              <el-dropdown-item command="top">上边框</el-dropdown-item>
              <el-dropdown-item command="right">右边框</el-dropdown-item>
              <el-dropdown-item command="bottom">下边框</el-dropdown-item>
              <el-dropdown-item command="left">左边框</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    
    <div id="excel-editor" ref="hotTableContainer" class="hot-table"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import Handsontable from 'handsontable';
import { registerLanguageDictionary, zhCN } from 'handsontable/i18n';
import 'handsontable/dist/handsontable.full.css';
import * as XLSX from 'xlsx';

// 注册中文语言包
registerLanguageDictionary(zhCN);

const hotTableContainer = ref(null);
const fileInput = ref(null);
let hotInstance = null;

// 格式化工具栏状态
const fontFamily = ref('SimSun');
const fontSize = ref(12);
const isBold = ref(false);
const isItalic = ref(false);
const isUnderline = ref(false);
const textColor = ref('#000000');
const bgColor = ref('#ffffff');

// 初始数据
const initialData = [
  ['', '', '', '', ''],
  ['', '', '', '', ''],
  ['', '', '', '', ''],
  ['', '', '', '', ''],
  ['', '', '', '', ''],
];

onMounted(() => {
  initializeTable();
});

onBeforeUnmount(() => {
  if (hotInstance) {
    hotInstance.destroy();
  }
});

// 初始化表格
const initializeTable = () => {
  hotInstance = new Handsontable(hotTableContainer.value, {
    data: initialData,
    rowHeaders: true,
    colHeaders: true,
    height: 'auto',
    licenseKey: 'non-commercial-and-evaluation', // 非商业用途许可证
    contextMenu: {
      items: {
        'row_above': {name: '在上方插入行'},
        'row_below': {name: '在下方插入行'},
        'col_left': {name: '在左侧插入列'},
        'col_right': {name: '在右侧插入列'},
        'remove_row': {name: '删除行'},
        'remove_col': {name: '删除列'},
        'undo': {name: '撤销'},
        'redo': {name: '重做'},
        'copy': {name: '复制'},
        'cut': {name: '剪切'},
        'alignment': {
          name: '对齐',
          submenu: {
            items: [
              {key: 'alignment:left', name: '左对齐'},
              {key: 'alignment:center', name: '居中对齐'},
              {key: 'alignment:right', name: '右对齐'},
              {key: 'alignment:justify', name: '两端对齐'},
              {key: 'alignment:top', name: '顶部对齐'},
              {key: 'alignment:middle', name: '垂直居中'},
              {key: 'alignment:bottom', name: '底部对齐'}
            ]
          }
        },
        'mergeCells': {name: '合并单元格'},
        'unmerge_cells': {name: '取消合并单元格'},
        'borders': {name: '边框'},
        'commentsAddEdit': {name: '添加/编辑注释'},
        'commentsRemove': {name: '删除注释'},
        'freeze_column': {name: '冻结该列'},
        'unfreeze_column': {name: '取消冻结列'}
      }
    },
    minSpareRows: 1,
    minSpareCols: 1,
    stretchH: 'all',
    width: '100%',
    autoColumnSize: true,
    manualColumnResize: true,
    manualRowResize: true,
    mergeCells: true,
    comments: true,
    formulas: true,
    language: 'zh-CN', // 设置语言为中文
    // 启用单元格样式
    cell: [],
    cells(row, col) {
      const cellProperties = {};
      
      // 使用自定义渲染器来应用样式
      cellProperties.renderer = function(instance, td, row, col, prop, value, cellProperties) {
        Handsontable.renderers.TextRenderer.apply(this, arguments);
        
        // 应用保存的样式
        if (cellProperties.style) {
          Object.assign(td.style, cellProperties.style);
        }
        
        return td;
      };
      
      return cellProperties;
    }
  });
  
  // 添加合并单元格的初始配置
  const plugin = hotInstance.getPlugin('mergeCells');
  
  // 监听选择事件，更新工具栏状态
  hotInstance.addHook('afterSelection', (row, column, row2, column2) => {
    updateToolbarState(row, column);
  });
};

// 更新工具栏状态
const updateToolbarState = (row, col) => {
  if (!hotInstance) return;
  
  const cellMeta = hotInstance.getCellMeta(row, col);
  const cellStyle = cellMeta.style || {};
  
  // 更新工具栏状态
  fontFamily.value = cellStyle.fontFamily || 'SimSun';
  fontSize.value = parseInt(cellStyle.fontSize) || 12;
  isBold.value = cellStyle.fontWeight === 'bold';
  isItalic.value = cellStyle.fontStyle === 'italic';
  isUnderline.value = cellStyle.textDecoration === 'underline';
  textColor.value = cellStyle.color || '#000000';
  bgColor.value = cellStyle.background || '#ffffff';
};

// 应用字体
const applyFontFamily = (value) => {
  applyStyle('fontFamily', value);
};

// 应用字号
const applyFontSize = (value) => {
  applyStyle('fontSize', `${value}px`);
};

// 切换加粗
const toggleBold = () => {
  isBold.value = !isBold.value;
  applyStyle('fontWeight', isBold.value ? 'bold' : 'normal');
};

// 切换斜体
const toggleItalic = () => {
  isItalic.value = !isItalic.value;
  applyStyle('fontStyle', isItalic.value ? 'italic' : 'normal');
};

// 切换下划线
const toggleUnderline = () => {
  isUnderline.value = !isUnderline.value;
  applyStyle('textDecoration', isUnderline.value ? 'underline' : 'none');
};

// 应用对齐方式
const applyAlignment = (alignment) => {
  const selectedRange = hotInstance.getSelectedRange();
  if (!selectedRange) return;
  
  const { from, to } = selectedRange[0];
  for (let row = from.row; row <= to.row; row++) {
    for (let col = from.col; col <= to.col; col++) {
      const cellMeta = hotInstance.getCellMeta(row, col);
      cellMeta.className = alignment;
      hotInstance.setCellMeta(row, col, 'className', alignment);
    }
  }
  hotInstance.render();
};

// 应用文字颜色
const applyTextColor = (color) => {
  const selectedRange = hotInstance.getSelectedRange();
  if (!selectedRange) return;
  
  const { from, to } = selectedRange[0];
  
  // 为每个选中的单元格创建或更新类
  for (let row = from.row; row <= to.row; row++) {
    for (let col = from.col; col <= to.col; col++) {
      // 获取当前单元格的类名
      let className = hotInstance.getCellMeta(row, col).className || '';
      
      // 移除旧的文字颜色类
      className = className.replace(/text-color-[a-f0-9]{6}/g, '');
      
      // 添加新的文字颜色类
      const colorClass = `text-color-${color.replace('#', '')}`;
      className = `${className} ${colorClass}`.trim();
      
      // 设置更新后的类名
      hotInstance.setCellMeta(row, col, 'className', className);
    }
  }
  
  // 添加自定义CSS规则
  const colorWithoutHash = color.replace('#', '');
  const styleElement = document.createElement('style');
  styleElement.textContent = `.text-color-${colorWithoutHash} { color: ${color} !important; }`;
  document.head.appendChild(styleElement);
  
  // 重新渲染表格
  hotInstance.render();
};

// 应用背景颜色
const applyBgColor = (color) => {
  const selectedRange = hotInstance.getSelectedRange();
  if (!selectedRange) return;
  
  const { from, to } = selectedRange[0];
  
  // 为每个选中的单元格创建或更新类
  for (let row = from.row; row <= to.row; row++) {
    for (let col = from.col; col <= to.col; col++) {
      // 获取当前单元格的类名
      let className = hotInstance.getCellMeta(row, col).className || '';
      
      // 移除旧的背景颜色类
      className = className.replace(/bg-color-[a-f0-9]{6}/g, '');
      
      // 添加新的背景颜色类
      const colorClass = `bg-color-${color.replace('#', '')}`;
      className = `${className} ${colorClass}`.trim();
      
      // 设置更新后的类名
      hotInstance.setCellMeta(row, col, 'className', className);
    }
  }
  
  // 添加自定义CSS规则
  const colorWithoutHash = color.replace('#', '');
  const styleElement = document.createElement('style');
  styleElement.textContent = `.bg-color-${colorWithoutHash} { background-color: ${color} !important; }`;
  document.head.appendChild(styleElement);
  
  // 重新渲染表格
  hotInstance.render();
};

// 应用样式
const applyStyle = (styleName, styleValue) => {
  const selectedRange = hotInstance.getSelectedRange();
  if (!selectedRange) return;
  
  const { from, to } = selectedRange[0];
  for (let row = from.row; row <= to.row; row++) {
    for (let col = from.col; col <= to.col; col++) {
      // 获取单元格元数据
      const cellMeta = hotInstance.getCellMeta(row, col);
      
      // 确保style对象存在
      if (!cellMeta.style) {
        cellMeta.style = {};
      }
      
      // 设置样式属性
      cellMeta.style[styleName] = styleValue;
      
      // 直接应用到DOM元素
      const td = hotInstance.getCell(row, col);
      if (td) {
        td.style[styleName] = styleValue;
      }
      
      // 对于颜色和背景色，我们需要使用renderer
      if (styleName === 'color' || styleName === 'background') {
        cellMeta.renderer = (instance, td, row, col, prop, value, cellProperties) => {
          Handsontable.renderers.TextRenderer.apply(this, arguments);
          
          // 应用所有已保存的样式
          if (cellProperties.style) {
            Object.assign(td.style, cellProperties.style);
          }
          
          return td;
        };
      }
    }
  }
  
  // 强制重新渲染表格
  hotInstance.render();
  hotInstance.refreshDimensions();
};

// 处理边框命令
const handleBorderCommand = (command) => {
  const selectedRange = hotInstance.getSelectedRange();
  if (!selectedRange) return;
  
  const { from, to } = selectedRange[0];
  const borderPlugin = hotInstance.getPlugin('customBorders');
  
  switch (command) {
    case 'all':
      borderPlugin.setBorders(from.row, from.col, to.row, to.col, {
        top: { width: 1, color: '#000' },
        right: { width: 1, color: '#000' },
        bottom: { width: 1, color: '#000' },
        left: { width: 1, color: '#000' }
      });
      break;
    case 'outer':
      // 设置外边框
      for (let row = from.row; row <= to.row; row++) {
        for (let col = from.col; col <= to.col; col++) {
          const borders = {};
          if (row === from.row) borders.top = { width: 1, color: '#000' };
          if (col === to.col) borders.right = { width: 1, color: '#000' };
          if (row === to.row) borders.bottom = { width: 1, color: '#000' };
          if (col === from.col) borders.left = { width: 1, color: '#000' };
          
          if (Object.keys(borders).length > 0) {
            borderPlugin.setBorders(row, col, row, col, borders);
          }
        }
      }
      break;
    case 'none':
      borderPlugin.clearBorders(from.row, from.col, to.row, to.col);
      break;
    case 'top':
      for (let col = from.col; col <= to.col; col++) {
        borderPlugin.setBorders(from.row, col, from.row, col, {
          top: { width: 1, color: '#000' }
        });
      }
      break;
    case 'right':
      for (let row = from.row; row <= to.row; row++) {
        borderPlugin.setBorders(row, to.col, row, to.col, {
          right: { width: 1, color: '#000' }
        });
      }
      break;
    case 'bottom':
      for (let col = from.col; col <= to.col; col++) {
        borderPlugin.setBorders(to.row, col, to.row, col, {
          bottom: { width: 1, color: '#000' }
        });
      }
      break;
    case 'left':
      for (let row = from.row; row <= to.row; row++) {
        borderPlugin.setBorders(row, from.col, row, from.col, {
          left: { width: 1, color: '#000' }
        });
      }
      break;
  }
  
  hotInstance.render();
};

// 保存数据
const saveData = () => {
  const data = hotInstance.getData();
  console.log('保存的数据:', data);
  // 这里可以添加API调用，将数据保存到后端
  ElMessage.success('数据保存成功');
};

// 导出Excel
const exportExcel = () => {
  const data = hotInstance.getData();
  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  XLSX.writeFile(wb, 'excel-export.xlsx');
  ElMessage.success('Excel导出成功');
};

// 导入Excel
const importExcel = () => {
  fileInput.value.click();
};

// 处理文件导入
const handleFileImport = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
    const jsonData = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
    
    hotInstance.loadData(jsonData);
    ElMessage.success('Excel导入成功');
    event.target.value = null; // 重置文件输入
  };
  reader.readAsArrayBuffer(file);
};

// 合并单元格
const mergeCells = () => {
  const plugin = hotInstance.getPlugin('mergeCells');
  const selectedRange = hotInstance.getSelectedRange();
  
  if (selectedRange) {
    const { from, to } = selectedRange[0];
    plugin.merge(from.row, from.col, to.row, to.col);
    hotInstance.render();
    ElMessage.success('单元格已合并');
  } else {
    ElMessage.warning('请先选择要合并的单元格');
  }
};

// 取消合并单元格
const unmergeCells = () => {
  const plugin = hotInstance.getPlugin('mergeCells');
  const selectedRange = hotInstance.getSelectedRange();
  
  if (selectedRange) {
    const { from } = selectedRange[0];
    plugin.unmerge(from.row, from.col);
    hotInstance.render();
    ElMessage.success('已取消合并');
  } else {
    ElMessage.warning('请先选择要取消合并的单元格');
  }
};
</script>

<style scoped>
.excel-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.format-toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.toolbar-group {
  display: flex;
  align-items: center;
  gap: 5px;
  border-right: 1px solid #ddd;
  padding-right: 10px;
  margin-right: 5px;
}

.toolbar-group:last-child {
  border-right: none;
}

.color-label {
  font-size: 12px;
  color: #606266;
  margin-right: 2px;
}

.active {
  background-color: #e6f7ff;
  color: #1890ff;
}

.hot-table {
  height: calc(100vh - 150px);
  overflow: hidden;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* Handsontable 对齐样式 */
:deep(.htLeft) {
  text-align: left;
}

:deep(.htCenter) {
  text-align: center;
}

:deep(.htRight) {
  text-align: right;
}

:deep(.htJustify) {
  text-align: justify;
}
</style>
